package edu.hawaii.myisern.action;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;

/**
 * Provides test cases.
 * 
 * @author Jon Lao
 * @author Jared Sunouchi
 * @author Chiao-Fen Zielinski-Liu
 */
public class TestLoginActionBean {

  /** Get the test host. */
  private String testHost = System.getProperty("test.host");
  private String pageTitle = "MyISERN 1.3 Login";
  private String username = "username";
  private String password = "password";
  
  /**
   * Tests the login function under normal situations.
   *
   * @throws Exception If problems occur
   */
  @Test
  @SuppressWarnings("deprecation") //TableCell.asText() is httpunit 1.5.3, needed due to Hackystat
  public void testLogin() throws Exception {
    WebConversation conversation = new WebConversation();
    
    String Url = testHost + "myisern-1-green/index.jsp";
    WebResponse response = conversation.getResponse(Url);
    assertEquals("Checking index.jsp retrieval", pageTitle, response.getTitle());
    
    WebForm loginForm = response.getFormWithID("LoginForm");
    WebRequest loginRequest = loginForm.getRequest();
    
    loginRequest.setParameter("username", "username");
    loginRequest.setParameter("password", "password");
    
    response = conversation.getResponse(loginRequest);
    loginRequest = loginForm.getRequest();
    
    assertEquals("Checking home.jsp retrieval", "MyISERN 1.3", response.getTitle());
    
    WebLink link = response.getLinkWith("Logout");
    link.click();
    response = conversation.getCurrentPage();

    assertEquals("Checking index.jsp retrieval after logout", pageTitle, 
        response.getTitle());
    
    loginForm = response.getFormWithID("LoginForm");
    loginRequest = loginForm.getRequest();
    
    loginRequest.setParameter(username, "user");
    loginRequest.setParameter(password, password);
    
    response = conversation.getResponse(loginRequest);
    loginRequest = loginForm.getRequest();
    
    assertEquals("Checking home.jsp retrieval", pageTitle, response.getTitle());
    
    loginForm = response.getFormWithID("LoginForm");
    loginRequest = loginForm.getRequest();
    
    loginRequest.setParameter(username, username);
    loginRequest.setParameter(password, "pass");
    
    response = conversation.getResponse(loginRequest);
    loginRequest = loginForm.getRequest();
    
    assertEquals("Checking home.jsp retrieval", pageTitle, response.getTitle());
  }
}